package com.caidanxiaoyuan.util;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author zhaoyulong
 *
 */
public class JsonUtil {

	private JsonUtil() {
	}

	private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

	private static final ObjectMapper objectMapper = new ObjectMapper();

	
	public static <T> String toJsonStr(T obj) {

		String jsonStr = null;

		try {
			jsonStr = objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			logger.error("Java对象转Json字符串出错！", e);
			throw new RuntimeException(e);
		}

		return jsonStr;
	}

	
	public static <T> T readValue(String jsonStr, Class<T> type) {

		T obj = null;

		try {
			obj = objectMapper.readValue(jsonStr, type);
		} catch (Exception e) {
			logger.error("Json字符串转Java对象出错！", e);
			throw new RuntimeException(e);
		}

		return obj;
	}

	
	public static <T> T readValue(String jsonStr, TypeReference<T> type) {

		T obj = null;

		try {
			obj = objectMapper.readValue(jsonStr, type);
		} catch (Exception e) {
			logger.error("Json字符串转Java对象出错！", e);
			throw new RuntimeException(e);
		}

		return obj;
	}

	public static <V extends Object> Map<String, V> toMap(String jsonStr) {
		Map<String, V> map = JSON.parseObject(jsonStr, Map.class);
		return map;
	}

	public static <T> List<T> getObjectList(String content, Class<T> elementType) {
		return getObject(content, objectMapper.getTypeFactory().constructParametricType(List.class, elementType));
	}

	public static <T> T getObject(String content, JavaType type) {

		try {
			return objectMapper.readValue(content, type);
		} catch (Throwable e) {
		}

		return null;
	}
}